import Vue from 'vue'
import Vuex from 'vuex'

//安装插件

Vue.use(Vuex)

//创建Vuex对象

const store = new Vuex.Store({
  state: {
    cartList: []
  },
  mutations: {
    addCount(state,payload){
      payload.count += 1;
    },
    addToCar(state,payload){
      state.cartList.push(payload)
    }

  },
  actions: {
    addCart(content, payload){
      return new Promise((resolve,reject)=> {
        let oldProduct = content.state.cartList.find(function(item){
          return item.iid === payload.iid
        })
        if(oldProduct){
          content.commit('addCount',oldProduct)
          resolve('数量加一')
        }else {
          payload.count = 1;
          content.commit('addToCar',payload)
          reject('添加成功')
        }
      })


    }
  }
})

//挂载

export default store